<?php
class ContentTypeController extends BackOfficeController
{
    public function actionAdd()
    {
        $contexts = null;
        if (isset($_POST['content_type']))
        {
            $contentType = $_POST['content_type'];
            $result = FSM::_run('Cms.ContentContext.getContexts', array(
                'contentType' => $contentType,
                'contextType' => 'edit',
            ));
            if ($result->hasErrors() == false){
                $contexts = $result->contexts;
                if (empty($contexts))
                    throw new CHttpException(500,Yii::t('Cms.ContentType','Sorry, this content type cannot be edited.'));
                if (count($contexts) == 1)
                    $this->redirect($contexts[0]->getUrl(array(
                        'id' => 0,
                    )));
            }
        }

        $this->render('add', array(
            'context' => $contexts
        ));
    }
    
    public function actionFind()
    {
        if (isset($_POST['content_type']))
        {
            $data = explode('.', $_POST['content_type']);
            if (is_array($data) && count($data) === 3)
            {
                list($module, , $model) = $data;
                $this->redirect(array('/'.$module.'/admin/'.$model.'/admin'));
            }
            else
            {
                //error
            }
        }

        $this->render('find', array());
    }
    
    public function actionAdmin()
    {
        $model=new ContentType('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['ContentType']))
            $model->attributes=$_GET['ContentType'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }
    
    public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                FSM::run('Cms.form.deleteByContentType', array('ids' => $ids));    
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.ContentType.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {                    
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
    }
}
